<template>
  <div class="Edit">
    <!-- 顶部标题 -->
    <top-title-bar>
      <template #left>
        <div class="left">
          <span class="iconfont icon-xiangzuo1" @click="$router.go(-1)"></span>
          <div class="title">
            {{ way == "release" ? "发布新话题" : "评论" }}
          </div>
        </div>
      </template>
      <template #right>
        <div class="right">
          <div class="title" @click="subFun">提交</div>
        </div>
      </template>
    </top-title-bar>

    <article v-if="way == 'release'">
      <div :class="['body', { con: imgsShow }]">
        <div class="title">
          <input
            type="text"
            placeholder="填写标题,5~32个字符"
            maxlength="32"
            v-model="newTitle"
          />
        </div>

        <div class="content">
          <textarea
            type="text"
            placeholder="填写内容,5~2000个字符"
            maxlength="2000"
            v-model="newDetail"
          ></textarea>
        </div>

        <div class="imgs">
          <van-uploader
            v-model="imgList"
            :after-read="afterRead"
            multiple
            :max-count="9"
          />
        </div>
      </div>

      <div class="foot">
        <p>你还可以输入{{ item.strLen }}个字符 上传{{ item.imgLen }}张图片</p>

        <div class="box">
          <!-- - 左边 -->
          <div class="left">
            <span class="iconfont icon-icon_xiaolian-xian" @click="$toast('表情包 暂未开饭')"></span>
            <span
              class="iconfont icon-paizhao"
              @click="imgsShow = !imgsShow"
            ></span>
            <span class="iconfont icon-fuhao-" @click="$toast('@ 暂未开饭')"></span>
            <span class="iconfont icon-huatifuhao" @click="$toast('话题链接 暂未开饭')"></span>
            <span class="iconfont icon-tianjia1" @click="$toast('添加 暂未开饭')"></span>
          </div>

          <!-- - 右边 -->
          <div class="right">
            <!-- <span>分类</span> -->
            <van-dropdown-menu direction="up" :class="{ con: tag_id != 0 }">
              <van-dropdown-item v-model="tag_id" :options="tagList" />
            </van-dropdown-menu>
          </div>
        </div>
      </div>
    </article>

    <article v-else-if="way == 'comment'">
      <div :class="['body', { con: imgsShow }]">
        <div class="icon-name-age-text">
          <div class="icon-name-age">
            <div class="icon"><img :src="item.icon" alt="" /></div>
            <div class="name-age">
              <div class="name">{{ item.name }}</div>
              <div
                :class="[
                  'age',
                  'iconfont',
                  { woman: item.gender == 1 },
                  item.gender == 2 ? 'icon-nan' : 'icon-nv',
                ]"
              >
                {{ item.age }}
              </div>
            </div>
          </div>
          <div class="text" @click="textHide = !textHide">
            <span :class="{ 'text-ellipsis-4': textHide }">{{
              item.commentContent
            }}</span>
          </div>
        </div>

        <div
          class="content"
          :style="{ top: way == 'comment' ? '160px' : '0px' }"
        >
          <textarea
            type="text"
            placeholder="填写内容,5~2000个字符"
            maxlength="2000"
            v-model="commentReply"
          ></textarea>
        </div>

        <div class="imgs">
          <van-uploader
            v-model="imgList"
            :after-read="afterRead"
            multiple
            :max-count="9"
          />
        </div>
      </div>

      <div class="foot">
        <p>你还可以输入{{ item.strLen }}个字符 上传{{ item.imgLen }}张图片</p>

        <div class="box">
          <!-- - 左边 -->
          <div class="left">
            <span
              class="iconfont icon-icon_xiaolian-xian"
              @click="$toast('暂无表情包')"
            ></span>
            <span
              class="iconfont icon-paizhao"
              @click="imgsShow = !imgsShow"
            ></span>
            <span
              class="iconfont icon-fuhao-"
              @click="$toast('暂不可@其他人')"
            ></span>
            <span
              class="iconfont icon-huatifuhao"
              v-if="way == 'release'"
            ></span>
            <span class="iconfont icon-tianjia1" v-if="way == 'release'"></span>
          </div>

          <!-- - 右边 -->
          <div class="right" v-if="way == 'release'">
            <!-- <span>分类</span> -->
            <van-dropdown-menu direction="up" :class="{ con: tag_id != 0 }">
              <van-dropdown-item v-model="tag_id" :options="tagList" />
            </van-dropdown-menu>
          </div>
        </div>
      </div>
    </article>
  </div>
</template>
  


<script>
import {
  getPostDetailJson,
  getPostCommentJson,
  getPostJson,
} from "../assets/api/posts.js";
import { getSpaceUserinfo } from "../assets/api/space.js";
import TopTitleBar from "../components/TopTitleBar.vue";
export default {
  data() {
    return {
      way: null, // 是发帖子还是 评论

      textHide: true, // 评论对象内容是否溢出隐藏

      userinfo: null, // 用户信息

      item: {}, // 显示需要评论的内容

      comment: null, //有两处地方用到 获取过程较复杂 获取一边就行

      commentReply: "", // 输入框双向绑定

      imgsShow: false, // 上传图片布局是否隐藏

      newTitle: "", //发布新帖子的标题

      newDetail: "", //发布新帖子的内容

      // 图片数组
      imgList: [
        // { url: "https://img01.yzcdn.cn/vant/leaf.jpg" },
        // Uploader 根据文件后缀来判断是否为图片文件
        // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
        // { url: "https://cloud-image", isImage: true },
      ],

      tag_id: 0,
      tagList: [
        { text: "分类", value: 0 },
        { text: "新款商品", value: 1 },
        { text: "活动商品", value: 2 },
      ],
    };
  },
  methods: {
    // 初始化数据
    dataInit() {
      this.wayInit();
      this.tagListInit();
      this.commentContentInit();
      this.userinfoInit();
    },

    // 初始化标签列表
    async tagListInit() {
      if ("categoryID" in this.$route.query) {
        let categoryID = this.$route.query.categoryID;
        let postData = await getPostJson();
        let obj = postData.postCategoryListSortBy0.find(
          (item) => item.category.categoryID == categoryID
        );
        let tags = obj.category.tags;
        this.tagList = [];
        tags.forEach(({ ID, name }) => {
          this.tagList.push({ text: name, value: ID });
        });
        console.log("取到的tags =>", tags, "tagList =>", this.tagList);
      }
    },

    // 用户信息
    userinfoInit() {
      this.$toast.loading({
        message: "正在拉取您的信息...",
        forbidClick: true,
        loadingType: "spinner",
        overlay: true,
        duration: 0,
      });
      getSpaceUserinfo({ user_id: "20096544" }).then((data) => {
        this.userinfo = data;
        console.log("get用户数据 =>", this.userinfo);
        this.$toast.success("拉取结束");
      });
    },

    // 初始化需要评论的内容 对象
    async commentContentInit() {
      if ("seq" in this.$route.query) {
        // 拿到参数
        let postID = this.$route.query.postID;
        let seq = this.$route.query.seq;
        console.log("得到的参数 postID => ", postID);
        console.log("得到的参数 seq => ", seq);

        // 拿到数据
        let data = await getPostDetailJson();

        this.item.imgLen = 9;
        this.item.strLen = 2000;
        let obj = data.postDetailList.find(
          (item) => item.post.postID == postID
        );
        if (seq == -1) {
          this.item.commentContent = this.HtmlToText(obj.post.detail);
          this.item.icon = obj.post.user.avatar;
          this.item.name = obj.post.user.nick;
          this.item.age = obj.post.user.age;
          this.item.gender = obj.post.user.gender;
        } else if (seq > 0) {
          let comment = {};
          if (seq > 20) {
            // 拿到第二页后全部评论
            let pageData = await getPostCommentJson();
            // 拿到页数
            let i = Math.floor(seq / 20);
            // 找到评论
            if (i < pageData.postCommentlList.length) {
              comment = pageData.postCommentlList[i - 1].comments.find(
                (item) => item.seq == seq
              );
            }
            // 找不到就往本地存储里找
            if (!comment || i >= pageData.postCommentlList.length) {
              let commentList = JSON.parse(localStorage.getItem("commentList"));
              if (!commentList) return this.$toast.fail("失败了");
              let index = commentList.findIndex(
                (item) => item.conment.seq == seq
              );
              if (index == -1) this.$toast.fail("失败了");
              else comment = commentList[index].conment;
              console.log(comment);
            }
          } else comment = obj.comments.find((item) => item.seq == seq);

          // 保存一下 提交时 也许用到
          this.comment = comment;

          this.item.commentContent = this.HtmlToText(comment.text);
          this.item.icon = comment.user.avatar;
          this.item.name = comment.user.nick;
          this.item.age = comment.user.age;
          this.item.gender = comment.user.gender;
        }
        this.$set(this.item, "response", "ok");
        console.log("这是初始化数据 item =>", this.item);
      } else console.log("缺少参数");
    },

    // 输入框输入事件
    inputCommentEvent(e) {
      let inp = e.target;
      this.item.commentReply = inp.value;
      console.log(inp.value.length);
      this.item.strLen = 2000 - inp.value.length;
      this.$set(this.item, "strLen", 2000 - inp.value.length);
    },

    // 初始化显示方式
    wayInit() {
      if ("way" in this.$route.query) this.way = this.$route.query.way;
      else this.way = "release";

      console.log("得到的参数 =>", this.way);
    },

    // 图片上传方法
    afterRead(file) {
      file.status = "uploading";
      file.message = "上传中...";

      setTimeout(() => {
        file.status = "done";
      }, 1000);
    },

    // html代码转成字符
    HtmlToText(html) {
      let text = html;
      text = text.split("<text>").join("");
      text = text.split("</text>").join("");
      text = text.split("<image>").join("");
      text = text.split("</image>").join("");
      return text;
    },

    // 提交按钮触发
    async subFun() {
      let { strLen } = this.item;
      if (2000 - strLen < 5) this.$toast("内容太少无法提交");
      else {
        if (this.way == "release") this.releaseSubFun();
        else if (this.way == "comment") this.commentSubFun();
      }
    },

    // 帖子提交
    releaseSubFun() {
      // 随机id
      let postID = Math.floor(
        (Math.random() * 51465146) / 2 + (Math.random() * 51465146) / 2
      );
      // 获取标题
      let title = this.newTitle;
      // 获取内容
      let detail = this.newDetail;
      // 获取图片数组
      let images = this.imgList.map((item) => item.content);
      // 取到当前时间
      let createTime = new Date().getTime();
      // 取到用户一些信息
      let { userID, nick, avatar, gender, age } = this.userinfo;
      // 获取标签id
      let tagid = this.tag_id;
      let obj = {
        postID,
        title,
        detail,
        images,
        score: 0,
        scoreTxt: "",
        hit: 0,
        commentCount: 0,
        notice: 0,
        weight: 0,
        isGood: 0,
        createTime,
        activeTime: 1667269115000,
        line: 0,
        user: {
          userID,
          nick,
          avatar,
          gender,
          age,
          role: 0,
          experience: 66315,
          credits: 0,
          identityTitle: "",
          identityColor: 0,
          level: 7,
          levelColor: 0,
          integral: 0,
          uuid: 0,
          integralNick: null,
          signature: null,
          medalList: null,
          nickColor: null,
          nightNickColor: null,
          userRemark: null,
          ipAddr: null,
        },
        ext: null,
        category: null,
        tagid,
        status: 0,
        praise: 0,
        voice: null,
        isAuthention: 0,
        isRich: 0,
        appOrientation: 0,
        isAppPost: 0,
        appVersion: null,
        appSize: 0.0,
        appSystem: null,
        appLogo: null,
        screenshots: null,
        appIntroduce: null,
        appUrl: null,
        appLanguage: null,
        isGif: 0,
        isTop: 0,
        state: 0,
      };

      // 先取出本地储存的数据
      let postList = JSON.parse(localStorage.getItem("postList"));
      if (!postList) postList = [];

      // 添加数据
      postList.push(obj);

      // 存放数据
      localStorage.setItem("postList", JSON.stringify(postList));

      console.log(
        "提交成功 这是数据 obj =>",
        obj,
        "这是所有数据 postList =>",
        postList
      );
      this.$toast("提交成功");

      // 回到上一路由
      this.$router.go(-1);
    },

    // 评论提交
    async commentSubFun() {
      // 随机id
      let commentID = Math.floor(
        (Math.random() * 51465146) / 2 + (Math.random() * 51465146) / 2
      );
      // 取到输入框内容
      let text = this.commentReply;
      // 取到图片数组
      let images = this.imgList.map((item) => item.content);
      // 取到当前时间
      let createTime = new Date().getTime();
      // 取到新楼
      let seq = this.$route.query.newSeq;
      // 取到用户一些信息
      let { userID, nick, avatar, gender, age } = this.userinfo;
      // 取到贴子id
      let postID = this.$route.query.postID;
      // 取到帖子标题
      let postListData = await getPostDetailJson();
      let postData = postListData.postDetailList.find(
        (item) => item.post.postID == postID
      );
      let postTitle = postData.post.title;
      let categoryTitle = postData.post.category.title;
      // 先设置空值
      let refComment = null;

      if (this.$route.query.seq > 0) {
        // 进行结构
        let {
          commentID,
          text,
          seq,
          user: { userID, nick },
        } = this.comment;

        // 回复对象
        refComment = {
          commentID,
          text,
          seq,
          userID,
          nick,
          state: 1,
          isTop: 0,
          userRemark: null,
        };
      }

      // 新建对象 把刚刚取到的对象放置进去
      let obj = {
        postID,
        conment: {
          commentID,
          text,
          images,
          voice: "",
          voiceTime: 0,
          score: 0,
          scoreTxt: "",
          seq,
          createTime,
          state: 1,
          isTop: 0,
          user: {
            userID,
            nick,
            avatar,
            gender,
            age,
            role: 0,
            experience: 6150,
            credits: 21,
            identityTitle: "",
            identityColor: 0,
            level: 4,
            levelColor: 4278255411,
            integral: 0,
            uuid: 0,
            integralNick: null,
            signature: null,
            medalList: [],
            nickColor: "#343434",
            nightNickColor: "#dbdbdb",
            userRemark: null,
            ipAddr: "",
          },
          post: { title: postTitle },
          category: { title: categoryTitle },
          refComment,
          scorelist: [],
          scoreUserCount: 0,
          scorecount: 0,
          praise: 0,
          remindUsers: null,
        },
      };

      // 先取出本地储存的数据
      let commentList = JSON.parse(localStorage.getItem("commentList"));
      if (!commentList) commentList = [];

      // 添加数据
      commentList.push(obj);

      // 存放数据
      localStorage.setItem("commentList", JSON.stringify(commentList));

      console.log(
        "提交成功 这是数据 obj =>",
        obj,
        "这是所有数据 commentList =>",
        commentList
      );
      this.$toast("提交成功");

      // 回到上一路由
      this.$router.go(-1);
    },
  },
  watch: {
    // 用于实时改变剩余图片长度
    imgList(val) {
      this.item.imgLen = val.length;
    },
    // 用于实时改变剩余字符长度
    commentReply(val) {
      this.item.strLen = 2000 - val.length;
    },
    // 用于实时改变剩余字符长度
    newDetail(val) {
      console.log(val);
      this.item.strLen = 2000 - val.length;
    },
  },
  created() {
    this.dataInit();
  },
  components: {
    TopTitleBar,
  },
};
</script>
  


<style lang="scss" scoped>
.Edit {
  .TopTitleBar {
    .left {
      display: flex;
      align-items: center;
      .icon-xiangzuo1 {
        font-weight: bold;
        color: #fff;
        font-size: 22px;
        margin-right: 4px;
      }
      .sort {
        ::v-deep .van-dropdown-menu {
          background-color: transparent;
          .van-dropdown-menu__bar {
            box-shadow: none;
            background-color: transparent;
            .van-dropdown-menu__title {
              color: #fff;
              &::after {
                opacity: 1;
                border-left-color: #fff;
                border-bottom-color: #fff;
              }
            }
          }
          .van-dropdown-item {
            .van-popup {
              display: flex;
              justify-content: space-around;
              .van-cell {
                padding: 0;
                display: flex;
                align-items: center;
                width: max-content;
                height: 50px;
                color: #969696;
                &.van-dropdown-item__option--active {
                  color: #15ca62;
                }
                .van-cell__value {
                  display: none;
                }
              }
            }
          }
        }
      }
    }
    .right {
      display: flex;
      align-items: center;

      .icon-xiaoxi,
      .icon-fangdajing {
        font-weight: bold;
        color: #fff;
        font-size: 22px;
      }
      .icon-fangdajing {
        font-size: 24px;
        margin-right: 10px;
      }
    }
  }

  .box {
    padding: 0 12px;

    .item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 74px;
      box-sizing: border-box;
      border-bottom: 1px solid #eaeaea;
      position: relative;
    }

    .img {
      width: 49px;
      height: 49px;
    }

    .title {
      width: calc(100% - 59px);
      box-sizing: border-box;
      padding-right: 25px;
      height: 49px;
      line-height: 49px;
      color: #3e3e3e;

      h4 {
        font-weight: normal;
      }
    }

    i {
      position: absolute;
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto;
      width: 9px;
      height: 17px;
      background-size: cover;
    }
  }

  article {
    position: fixed;
    top: 50px;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 10;
    min-width: 320px;
    max-width: 750px;
    margin: auto;

    .body {
      padding: 0 12px;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 90px;
    }

    .title {
      input {
        display: block;
        border: 0;
        padding: 0;
        height: 58px;
        border-bottom: 1px solid #eaeaea;
        width: 100%;
        outline: none;
        color: #343434;
      }
    }

    .content {
      position: absolute;
      top: 59px;
      bottom: 0;
      left: 12px;
      right: 12px;
      margin: auto;

      textarea {
        display: block;
        color: #646464;
        border: 0;
        padding: 0;
        padding: 12px 0;
        outline: none;
        line-height: 17px;
        width: 100% !important;
        min-height: 300px;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
      }
    }

    .foot {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      height: max-content;
      width: 100%;
      background-color: #fafafa;

      p {
        height: 40px;
        line-height: 40px;
        box-sizing: border-box;
        border-top: 1px solid #e7e7e7;
        color: #17ca63;
        font-size: 12px;
        padding: 0 12px;
      }

      .box {
        padding: 0 12px 0 10px;
        height: 49px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;
        border-top: 1px solid #eaeaea;
        color: #17ca63;
        font-size: 12px;
      }

      .left {
        display: flex;

        span {
          display: block;
          background-size: 204px 25px;
          width: 25px;
          height: 25px;
          margin-right: 20px;

          &:nth-child(2) {
            background-size: 204px 25px;
            width: 25px;
            height: 23px;
          }

          &:nth-child(3) {
            background-size: 204px 25px;
            width: 23px;
            height: 23px;
          }

          &:nth-child(4) {
            background-size: 204px 25px;
            width: 21px;
            height: 21px;
          }

          &:nth-child(5) {
            background-size: 204px 25px;
            width: 24px;
            height: 24px;
          }
        }
      }

      .right {
        span {
          display: block;
          height: 28px;
          line-height: 28px;
          text-align: center;
          background-color: #0cc85c;
          border-radius: 14px;
          color: #fff;
          font-size: 14px;
          padding: 0 8px;
          width: calc(4em + 16px);
          box-sizing: border-box;
        }
      }
    }
  }

  article .content textarea::-webkit-scrollbar,
  article .content textarea::-webkit-scrollbar-thumb {
    width: 0;
    height: 0;
  }
  article {
    .body {
      background-color: #fff;
      .icon-name-age-text {
        padding: 10px 0;
        .icon-name-age {
          display: flex;
          height: 40px;
          align-items: center;
          .icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            overflow: hidden;
            margin-right: 8px;
          }
          .name-age {
            flex: 1;
            .name {
              font-size: 14px;
            }
            .age {
              font-size: 12px;
              margin-top: 2px;
              border-radius: 4px;
              background-color: #1dc8f0;
              width: max-content;
              padding: 0 4px;
              color: #fff;
              &.woman {
                background-color: #f452a2;
              }
              &::before {
                margin-right: 2px;
              }
            }
          }
        }
        .text {
          background-color: #f0f0f0;
          padding: 5px 10px;
          border-radius: 4px;
          margin-top: 10px;
          height: 80px;
          font-size: 14px;
          line-height: 20px;
          overflow-y: scroll;
          overflow-x: hidden;
          word-break: break-all;

          &::-webkit-scrollbar {
            width: 4px;
          }

          &::-webkit-scrollbar-thumb {
            background-color: #15ca62;
            border-radius: 4px;
          }

          &:active {
            opacity: 0.9;
            color: #607d8b;
            background-color: #fafafa;
          }
          span {
            height: 80px;
          }
        }
      }
      .content {
        transition: all 0.3s linear;
        font-size: 14px;
        overflow: hidden;
        textarea {
          color: #000000;
          padding: 10px 0;
          box-sizing: border-box;
          min-height: unset;

          &::-webkit-scrollbar {
            width: 4px;
          }

          &::-webkit-scrollbar-thumb {
            background-color: #15ca62;
            border-radius: 4px;
          }
        }
      }
      ::v-deep .imgs {
        transition: all 0.3s linear;
        padding: 10px;
        background-color: #fafafa;
        box-shadow: 0 0px 10px #f0f0f0;
        display: block;
        position: absolute;
        left: 0;
        bottom: -100px;
        right: 0;
        height: 80px;
        .van-uploader {
          width: 100%;
          overflow-x: scroll;
          overflow-y: hidden;
          &::-webkit-scrollbar,
          &::-webkit-scrollbar-thumb {
            width: 0;
            height: 0;
          }
          .van-uploader__wrapper {
            flex-wrap: nowrap;
            .van-uploader__upload {
              flex-shrink: 0;
              background-color: #bbb;
              border-radius: 4px;
            }
            .van-uploader__preview {
              height: 80px;
              margin-bottom: 0;
              box-shadow: 0 0 4px 0 rgba($color: #000000, $alpha: 0.3),
                0 0 80px 0 inset rgba($color: #000000, $alpha: 0.2);
            }
          }
        }
      }
      &.con {
        // bottom: 190px;
        .content {
          bottom: 100px;
          textarea {
            height: 100%;
            margin: auto;
          }
        }
        .imgs {
          bottom: 0;
        }
      }
    }
    .foot {
      .box {
        .left {
          .iconfont {
            display: flex;
            align-items: center;
            justify-content: center;
            color: #646464;
          }
          .icon-icon_xiaolian-xian {
            font-size: 20px;
          }
          .icon-paizhao {
            font-size: 30px;
          }
          .icon-fuhao- {
            font-size: 22px;
          }
          .icon-huatifuhao {
            font-size: 28px;
          }
          .icon-tianjia1 {
            font-size: 20px;
          }
        }
        .right {
          ::v-deep .van-dropdown-menu {
            .van-dropdown-menu__bar {
              box-shadow: none;
              span {
                width: max-content;
                background-color: #fff;
                color: #646464;
                border: 1px solid #646464;
                &::after {
                  content: none;
                }
              }
            }
            .van-dropdown-item__option--active .van-cell__title span {
              border-color: #15ca62;
              background-color: #15ca62;
              color: #fff;
            }
            &.con {
              .van-dropdown-menu__title {
                color: #fff;
                background-color: #15ca62;
                border-color: #15ca62;
              }
            }
          }
          ::v-deep .van-popup {
            display: flex;
            flex-wrap: wrap;
            padding: 10px;
            .van-cell {
              width: max-content;
              padding: 0;
              margin-right: 8px;
              margin-bottom: 5px;
              span {
                padding: 0 15px;
                width: max-content;
                background-color: #fff;
                border: 1px solid #646464;
                color: #646464;
              }
            }
          }
          ::v-deep .van-cell__value {
            display: none;
          }
        }
      }
    }
  }
}
</style>